/**
 * class name: idle$,
 * copyright: maximus zhang,
 * License: MIT-LICENSE,
 * contact: maximus.zhang@gmail.com,
 * required-js: http://hcjs.googlecode.com/svn/trunk/hc.js,
 * update: http://hcjs.googlecode.com/svn/trunk/idle.js
 *
 */
function idle$(){/*{data},{cfg},{fn}*/
    var A = arguments,
        _ = this;
    _.data = ext$( { idle: 4, user: '', module: 'Idle', mdlid: 0, locref: '' }, A[0] );
    _.cfg = ext$({
        url: "idle.php",
        dfn: [
            [0,60,29,false],
            [61,300,49,false],
            [301,600,69,false],
            [601,900,89,false],
            [901,1800,109,false],
            [1801,3600,129,false]
            ],
        step: 29 }, A[1]);
    _.fn = ext$({ idle: function(a){;} }, A[2]);

    _.uitype = 'idle$';

    _.last = _._1st = now$(2);

    _.beep = parseInt(_._1st/1000, 10)%_.cfg.step;
    _.bound = false;

    _.reset$ = function(){_.last = now$(2);};

    _.state$ = function(t){
        for (var i = 0, L = _.cfg.dfn.length; i<L; i++) {
            if ( t>=_.cfg.dfn[i][0] && t<=_.cfg.dfn[i][1] ) {
                if ( _.cfg.dfn[i][3] ) {
                    return 0;
                } else {
                    for (var j = 0; j<L; j++) {
                        _.cfg.dfn[j][3] = false;
                    }

                    _.cfg.dfn[i][3] = true;
                    _.cfg.step = _.cfg.dfn[i][2];

                    return (1+i);
                }
            }
        }
        return 0;
    };

    _.exec$ = function(){
        _.data = ext$( _.data, arguments[0] );
        var idle = aja$({ url: _.cfg.url, data: _.data }, {
            finish : function(a){
                var v = duc$(a);

                if ( v.length>0 ) {
                    if ( _.fn.hasOwnProperty(v) ) {
                        _.fn[v]();
                    } else {
                        try {
                            _.fn.idle(v);
                        } catch (e) {
                            ex$(e);
                        }
                    }
                }
            },
            fail : function(a){
                var v = duc$(a); ex$(v);
            }
        } );
    };

    _.init$ = function(){
        if ( !_.bound ) {
            bind$(me, 'keydown', _.reset$);
            bind$(me, 'mousemove', _.reset$);
            _.bound = true;
        }

        var tt = now$(2);
        _.data.idle = _.state$( parseInt( (tt-_.last)/1000, 10 ) );

        if ( _.data.idle!==0 || (parseInt((tt-_._1st)/1000,10) % _.cfg.step)==_.beep ) {
            _.exec$();
        }
    return _;
    };

    _.go$ = function(){
        _.run = setInterval(_.init$, 1000);
    return _;
    };

    _.remove$ = function(){
        unbind$(me, 'keydown', _.reset$);
        unbind$(me, 'mousemove', _.reset$);
        for ( x in _ ){
            delete _[x];
        }
        _ = null;
    };
}